package cn.cs.mathgo.sso.service.Impl;

import cn.cs.mathgo.admin.modules.sys.feign.MenuFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Component("resourceService")
public class ResourceServiceImpl {
    @Autowired
    private MenuFeignClient menuFeignClient;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        User principal=null;
        try {
             principal  = (User) authentication.getPrincipal();
        }catch (Exception e){
            return  false;
        }


        boolean hasPermission = false;

        if(principal instanceof UserDetails){

            String username = ((UserDetails)principal).getUsername();
            if(antPathMatcher.match("admin*",username)){
                return true;
            }
            if(antPathMatcher.match("sigmajy*",username)){
                return true;
            }
            //读取用户所有权限的url，需要查询数据库
            R r = menuFeignClient.getLinkByUser(username);

            if(!"0".equals( r.get("code")+"")){
                return false;
            }

            List<String> list = r.get("list")!=null? (ArrayList)r.get("list"):new ArrayList();
            // List<String> list=new ArrayList();
            for(String url : list){
                String[] split = url.split(",");

                if(antPathMatcher.match(split[0], request.getRequestURI())){
                    if(split.length==2&& org.apache.commons.lang3.StringUtils.isNotBlank(split[1])){
                        String method = request.getMethod();
                        if(!method.equals(split[1])){
                            hasPermission = false ;
                            break ;
                        }
                    }else{
                        hasPermission = true ;
                        break ;
                    }

                }
            }
        }
        return hasPermission;
    }
}
